use actix_web::{delete, get, post, put, web, HttpRequest};

use log::{info, trace};
use rbase::{
    define::{ApiError, ApiResponse},
    id_utils::{opt_id2str, opt_str2id},
};
use rbase_iam::rest_api::service::auth_check::get_user_from_request;
use serde::{Deserialize, Serialize};

use crate::{
    db::entities::task::Model,
    rest_api::{
        api_knowledge,
        service::srv_task::{self},
    },
};

use anyhow::Result;
use rbase::id_utils::{id2str, str2id};

#[derive(Clone, Debug, Deserialize)]
pub struct CreateParams {
    pub name: String,

    pub scheduler_id: String,

    pub knowledge_ids: Vec<String>,
}

#[derive(Clone, Debug, Deserialize)]
pub struct UpdateParams {
    #[serde(default)]
    pub name: Option<String>,

    #[serde(default)]
    pub status: Option<i64>,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct Task {
    pub id: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub owner_id: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub scheduler_id: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<i64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_at: Option<i64>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub modified_at: Option<i64>,
}

impl Task {
    pub fn from_model(entity: &Model) -> Self {
        Task {
            id: id2str(entity.id),
            name: entity.name.clone(),
            created_at: entity.created_at,
            modified_at: entity.modified_at,
            owner_id: opt_id2str(&entity.owner_id),
            scheduler_id: opt_id2str(&entity.scheduler_id),
            status: entity.status,
        }
    }

    pub fn to_model(&self) -> Result<Model> {
        Ok(Model {
            id: str2id(&self.id)?,
            name: self.name.clone(),
            created_at: self.created_at,
            modified_at: self.modified_at,
            owner_id: opt_str2id(&self.owner_id)?,
            scheduler_id: opt_str2id(&self.scheduler_id)?,
            status: self.status,
        })
    }
}

#[derive(Deserialize, Debug)]
pub struct SearchParams {
    #[serde(default)]
    pub scheduler_id: Option<String>,

    #[serde(default)]
    pub name: Option<String>,

    #[serde(default)]
    pub offset: Option<u64>,

    #[serde(default)]
    pub limit: Option<u64>,

    #[serde(default)]
    pub order_by: Option<String>,

    #[serde(default)]
    pub order: Option<String>,
}

#[get("/api/v1/tasks")]
async fn list_tasks(req: HttpRequest, query_params: web::Query<SearchParams>) -> Result<ApiResponse, ApiError> {
    let task_search_params = query_params.into_inner();
    trace!("list_tasks query: {:?}", task_search_params);
    let user_token = get_user_from_request(&req)?;
    let (tasks, total) = srv_task::search(&user_token, &task_search_params).await?;
    trace!("search return {:?}", tasks);
    Ok(ApiResponse::datas(tasks, total))
}

#[post("/api/v1/tasks")]
async fn create_task(req: HttpRequest, req_body: String) -> Result<ApiResponse, ApiError> {
    trace!("create_task body: {}", req_body);
    let user_token = get_user_from_request(&req)?;
    let new_task: CreateParams = serde_json::from_str(&req_body)?;
    let task = srv_task::create_task(&user_token, &new_task).await?;
    Ok(ApiResponse::data(task))
}

#[get("/api/v1/tasks/{id}")]
async fn get_task(req: HttpRequest, path_params: web::Path<String>) -> Result<ApiResponse, ApiError> {
    let task_id = path_params.into_inner();
    trace!("get_task path: {:?}", task_id);
    let user_token = get_user_from_request(&req)?;
    let task = srv_task::find_task_by_id(&user_token, &task_id).await?;
    Ok(ApiResponse::data(task))
}

#[delete("/api/v1/tasks/{id}")]
async fn delete_task(req: HttpRequest, path_params: web::Path<String>) -> Result<ApiResponse, ApiError> {
    trace!("delete_task path: {:?}", path_params);
    let user_token = get_user_from_request(&req)?;
    let task_id = path_params.into_inner();
    srv_task::delete_task_by_id(&user_token, &task_id).await?;
    Ok(ApiResponse::success())
}

#[put("/api/v1/tasks/{id}")]
async fn update_task(req: HttpRequest, req_body: String, path_params: web::Path<String>) -> Result<ApiResponse, ApiError> {
    trace!("update_task path: {:?}, body: {}", path_params, req_body);
    let user_token = get_user_from_request(&req)?;
    let new_task: UpdateParams = serde_json::from_str(&req_body)?;

    let task_id = path_params.into_inner();
    srv_task::update_task_by_id(&user_token, &task_id, &new_task).await?;
    Ok(ApiResponse::success())
}

#[get("/api/v1/tasks/{id}/knowledge")]
async fn get_task_knowledge(req: HttpRequest, path_params: web::Path<String>, query_params: web::Query<api_knowledge::SearchParams>) -> Result<ApiResponse, ApiError> {
    let task_id = path_params.into_inner();
    trace!("get_task_knowledge path: {:?}", task_id);
    let user_token = get_user_from_request(&req)?;
    let (knowledge, total) = srv_task::search_task_knowledge(&user_token, &task_id, &query_params).await?;
    Ok(ApiResponse::datas(knowledge, total))
}

pub fn config(cfg: &mut web::ServiceConfig) {
    info!("Configuring task APIs");
    cfg.service(list_tasks);
    cfg.service(create_task);
    cfg.service(get_task);
    cfg.service(delete_task);
    cfg.service(update_task);
    cfg.service(get_task_knowledge);
}
